<!--
*@description 历史处方
*@fileName his-prescription.vue
*@author wxl
*@date 2025/05/3 21:28:31
!-->
<template>
  <div class="vue-box cdf">
    <div class="search-card">
      <div class="search-body">
        <el-form :inline="true" :model="formData" class="demo-form-inline">
          <el-form-item label="患者信息">
            <el-input v-model="formData.psn_name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="订单编号">
            <el-input v-model="formData.OnlineInquiryNo" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="处方单号">
            <el-input v-model="formData.electronicPrescriptionNo" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker
              type="daterange"
              v-model="formData.date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="处方类型">
            <el-select v-model="formData.PrescriptionType" placeholder="请选择">
              <el-option v-for="item in dicts.PrescriptionType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="病种类型">
            <el-select v-model="formData.CirculationType" placeholder="请选择">
              <el-option label="普通" value="1" />
              <el-option label="慢病" value="3" />
              <el-option label="统筹" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="问诊药店">
            <el-input v-model="formData.fixmedins_name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="医师">
            <el-input v-model="formData.dr_name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="药师">
            <el-input v-model="formData.pharName" placeholder="请输入" />
          </el-form-item>
          <el-form-item>
            <el-button class="btn" type="primary" @click="onSearch">搜索</el-button>
            <el-button type="default" plain icon="el-icon-Refresh" @click="sa.f5CurrView()">重置</el-button>
            <el-button type="primary" plain icon="el-icon-Share" @click="batchCirculation" :disabled="selectedRows.length === 0">批量流转</el-button>
            <el-button type="primary" plain icon="el-icon-Printer" @click="batchPrint" :disabled="selectedRows.length === 0">批量打印</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="c-card flex1 table-box">
      <div class="table-body">
        <el-table :data="tableData" :row-key="getRowKeys" stripe style="width: 100%; height: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" reserve-selection />
          <!-- 序号 -->
          <!-- <el-table-column label="编号" type="index" width="60"></el-table-column> -->
          <el-table-column v-for="(item, index) in tableCfg" :key="index" :prop="item.prop" :label="item.label" :width="item.width">
            <template #default="scope">
              <span>
                {{ item.formatter ? item.formatter(scope.row[item.prop]) : scope.row[item.prop] }}
              </span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="250" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" icon="el-icon-View" @click="seePrescribe(scope.row)">查看处方单</el-button>
              <el-button type="success" size="small" icon="el-icon-Share" v-if="scope.row.CirculationType != '1'" @click="circulatePrescription(scope.row)">流转处方</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <table-pagin
        :page-no="pagin.pageNo"
        :page-size="pagin.pageSize"
        :total="pagin.total"
        @handleCurrentChange="handleCurrentChange"
        @handleSizeChange="handleSizeChange"
      />
    </div>
    <el-dialog class="os-dialog" v-model="dialogVisible" title="处方单" width="730px" append-to-body>
      <div class="prescription-url">
        <img :src="prescriptionUrl" alt="处方单" ref="printImage"/>
      </div>
      <template #footer>
        <div class="aicjcsb margin-lr margin-bottom">
          <el-button type="success" icon="el-icon-Bottom" @click="savePrescript">保存处方</el-button>
          <div class="jcfe flex1">
            <el-button plain @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="printPrescript"> 打印处方 </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="goods-list">
import { reactive, onMounted, ref } from 'vue'
// import {useRouter} from 'vue-router'
import tablePagin from '@/sa-frame/com/pagin/table-pagin.vue'
import dicts from '@/utils/dict.js'
const formData = reactive({})
const pagin = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
  server_time: '',
})

const tableCfg = ref([
  {
    label: '订单编号',
    prop: 'OnlineInquiryNo',
    width: 200,
  },
  {
    label: '处方单号',
    prop: 'electronicPrescriptionNo',
    width: 200,
  },
  {
    label: '处方开具时间',
    prop: 'electronicPrescriptionTime',
    width: 150,
  },
  {
    label: '患者姓名',
    prop: 'psn_name',
  },
  {
    label: '性别',
    prop: 'sex',
    formatter: (value) => {
      return dicts.sex.find((item) => item.value == value)?.label
    },
  },
  {
    label: '年龄',
    prop: 'age',
  },
  {
    label: '处方类型',
    prop: 'PrescriptionType',
    formatter: (value) => {
      return dicts.PrescriptionType.find((item) => item.value == value)?.label
    },
  },
  {
    label: '病种类型',
    prop: 'CirculationType',
    formatter: (value) => {
      const types = {
        '1': '普通',
        '2': '统筹',
        '3': '慢病'
      }
      return types[value] || ''
    },
  },
  {
    label: '问诊药店',
    prop: 'fixmedins_name',
    width: 150,
  },
  {
    label: '临床诊断',
    prop: 'Symptom',
    width: 150,
  },
  {
    label: '诊断结果',
    prop: 'diag_name',
    width: 150,
  },
  {
    label: '医师',
    prop: 'dr_name',
  },
  {
    label: '药师',
    prop: 'pharName',
  },
])

const tableData = ref([])
// 已选择行
const selectedRows = ref([])
// 处方单
const prescriptionUrl = ref('')
const dialogVisible = ref(false)
const curItem = ref({})
const printImage = ref(null);

// 组件加载时触发
onMounted(() => {
  f5()
})

// 搜索
function onSearch() {
  pagin.pageNo = 1
  f5()
}

// ------------------ 查找数据 ------------------
const f5 = function () {
  let params = {
    pageindex: pagin.pageNo - 1,
    pagesize: pagin.pageSize,
    ...formData,
    begintime: formData.date ? formData.date[0] : '',
    endtime: formData.date ? formData.date[1] : '',
  }
  sa.ajax('/api/webPres/presList', params, function (res) {
    tableData.value = res.data // 数据
    pagin.total = Number(res.totalItems)
    pagin.server_time = res.server_time
  })
}
// 表格页码切换
function handleCurrentChange(pageNo) {
  pagin.pageNo = pageNo
  console.log(' pagin.pageNo', pagin.pageNo)
  f5()
}
// 表格size修改
function handleSizeChange(pageSize) {
  pagin.pageSize = pageSize
  f5()
}
// 表格行选择
function handleSelectionChange(val) {
  console.log('handleSelectionChange', val)
  selectedRows.value = val
}
function getRowKeys(row) {
  return row.electronicPrescriptionNo
}
// 批量上线
function multOnline() {
  sa.confirm('确定批量上线？', function () {
    // sa.ajax('/api/fund/storeInformationList', {
    //    ...formData
    // }, function(res) {
    //    tableData.value = res.data;	// 数据
    //    pagin.total = Number(res.totalItems);
    // }
    // )
  })
}

// 查看处方单
function seePrescribe(row) {
  console.log('row', row)
  if(!row.electronicPrescriptionNo) {
    sa.msg('处方单号为空，无法查看处方单')
    return
  }
  sa.ajax(
    '/api/webPres/queryPresUrl',
    {
      electronicPrescriptionNo: row.electronicPrescriptionNo,
    },
    function (res) {
      if (res.code == 1) {
        prescriptionUrl.value = res.data.AccessoryUrl
        dialogVisible.value = true
        curItem.value = row
      }
    }
  )
}

// 单个处方流转
function circulatePrescription(row) {
  if (!row.electronicPrescriptionNo) {
    sa.msg('处方单号为空，无法流转');
    return;
  }
  
  sa.confirm(`确定要流转处方 ${row.electronicPrescriptionNo} 吗？`, function() {
    sa.ajax('/api/webPres/presCirculationByNo', {
      electronicPrescriptionNo: row.electronicPrescriptionNo
    }, function(res) {
      if (res.code === 1) {
        sa.msg('处方流转成功');
        f5(); // 刷新表格数据
      } else {
        sa.msg(res.msg || '处方流转失败');
      }
    });
  });
}

// 批量流转处方
function batchCirculation() {
  if (selectedRows.value.length === 0) {
    sa.msg('请先选择要流转的处方');
    return;
  }
  
  sa.confirm(`确定要流转选中的 ${selectedRows.value.length} 个处方吗？`, function() {
    const promises = selectedRows.value.map(row => {
      return new Promise((resolve) => {
        if (!row.electronicPrescriptionNo) {
          resolve({ success: false, message: `处方单号为空，无法流转`, prescriptionNo: row.electronicPrescriptionNo });
          return;
        }
        
        sa.ajax('/api/webPres/presCirculationByNo', {
          electronicPrescriptionNo: row.electronicPrescriptionNo
        }, function(res) {
          resolve({ 
            success: res.code === 1, 
            message: res.msg || '流转成功', 
            prescriptionNo: row.electronicPrescriptionNo 
          });
        }, function(err) {
          resolve({ 
            success: false, 
            message: '请求失败', 
            prescriptionNo: row.electronicPrescriptionNo 
          });
        });
      });
    });
    
    Promise.all(promises).then(results => {
      const successCount = results.filter(r => r.success).length;
      const failCount = results.length - successCount;
      
      if (failCount > 0) {
        const failMessages = results.filter(r => !r.success).map(r => `${r.prescriptionNo}: ${r.message}`).join('\n');
        sa.alert(`部分处方流转失败:\n${failMessages}`);
      }
      
      if (successCount > 0) {
        sa.msg(`成功流转 ${successCount} 个处方`);
        f5(); // 刷新表格数据
      }
    });
  });
}

// 批量打印处方
function batchPrint() {
  if (selectedRows.value.length === 0) {
    sa.msg('请先选择要打印的处方');
    return;
  }
  
  sa.confirm(`确定要打印选中的 ${selectedRows.value.length} 个处方吗？`, function() {
    // 创建一个隐藏的iframe用于批量打印
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>批量打印处方</title>
          <style>
            @page {
              size: auto;
              margin: 0;
            }
            body { 
              margin: 0; 
              padding: 20px; 
              display: flex;
              flex-direction: column;
              align-items: center;
              width: 100vw; 
              min-height: 100vh; 
            }
            .prescription-image { 
              width: auto;
              height: auto;
              max-width: 100%;
              max-height: 100vh;
              object-fit: contain;
              margin-bottom: 20px;
              page-break-after: always;
            }
            .prescription-image:last-child {
              page-break-after: avoid;
            }
            .prescription-title {
              font-size: 16px;
              font-weight: bold;
              margin-bottom: 10px;
            }
          </style>
        </head>
        <body>
          <div id="print-container"></div>
        </body>
      </html>
    `);
    printWindow.document.close();
    
    // 获取所有选中处方的图片URL
    let loadedCount = 0;
    const totalToLoad = selectedRows.value.length;
    const container = printWindow.document.getElementById('print-container');
    
    // 显示加载提示
    container.innerHTML = '<p>正在加载处方图片...</p>';
    
    selectedRows.value.forEach((row, index) => {
      if (!row.electronicPrescriptionNo) {
        loadedCount++;
        checkIfAllLoaded();
        return;
      }
      
      sa.ajax(
        '/api/webPres/queryPresUrl',
        {
          electronicPrescriptionNo: row.electronicPrescriptionNo,
        },
        function (res) {
          if (res.code == 1) {
            // 清除加载提示（仅在第一个处方加载时）
            if (loadedCount === 0) {
              container.innerHTML = '';
            }
            
            if (container) {
              // 添加患者信息作为标题
              const title = printWindow.document.createElement('div');
              title.className = 'prescription-title';
              // title.textContent = `${row.psn_name}-${row.electronicPrescriptionNo}`;
              container.appendChild(title);
              
              // 添加处方图片
              const img = printWindow.document.createElement('img');
              img.src = res.data.AccessoryUrl;
              img.className = 'prescription-image';
              img.alt = `处方单-${row.electronicPrescriptionNo}`;
              container.appendChild(img);
            }
          }
          loadedCount++;
          checkIfAllLoaded();
        },
        function() {
          loadedCount++;
          checkIfAllLoaded();
        }
      );
    });
    
    function checkIfAllLoaded() {
      if (loadedCount >= totalToLoad) {
        // 所有图片加载完成后执行打印
        setTimeout(() => {
          printWindow.focus();
          printWindow.print();
        }, 1300);
      }
    }
  });
}

// 保存处方
async function savePrescript() {
  // const link = document.createElement('a');
  // link.href = prescriptionUrl.value;
  // link.download = curItem.value.psn_name + '处方单.png';
  // link.style.display = 'none'; // 隐藏链接
  // document.body.appendChild(link);
  // link.click();
  // document.body.removeChild(link);
  let protocol = window.location.protocol
  // 如果域名是http 那么图片的地址也改成http
  if (protocol == 'http:') {
    prescriptionUrl.value = prescriptionUrl.value.replace('https', 'http')
  }
  let url = prescriptionUrl.value
  let data = await fetch(url)
    .then((response) => response.blob())
    .then((res) => {
      console.log(res, '==============')
      let blod = new Blob([res])
      let name = curItem.value.psn_name + '处方单.png';
      downloadBlob(blod, name)
    })
}

function downloadBlob(blob, fileName) {
  try {
    const href = window.URL.createObjectURL(blob) //创建下载的链接
    if (window.navigator.msSaveBlob) {
      window.navigator.msSaveBlob(blob, fileName)
    } else {
      const downloadElement = document.createElement('a')
      downloadElement.href = href
      downloadElement.target = '_blank'
      downloadElement.download = fileName
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
    }
  } catch (e) {
    console.log('下载失败')
  }
}

function printPrescript() {
  const printWindow = window.open('', '_blank');
  printWindow.document.write(`
    <html>
      <head>
        <title>打印图片</title>
        <style>
          @page {
            size: auto;
            margin: 0;
          }
          body { 
            margin: 0; 
            padding: 0; 
            display: flex;
            flex-direction: column; /* 改为列布局 */
            align-items: center; /* 左对齐 */
            width: 100vw; 
            min-height: 100vh; 
          }
          img { 
            width: auto;
            height: auto;
            max-width: 100%;
            max-height: 100vh;
            object-fit: contain;
            margin-top: 0; /* 确保顶部无间距 */
          }
        </style>
      </head>
      <body>
        <img src="${printImage.value.src}">
      </body>
    </html>
  `);
  printWindow.document.close();
  printWindow.focus();
  
  printWindow.onload = function() {
    setTimeout(() => {
      printWindow.print();
      // printWindow.close();
    }, 500);
  };
}
// 对外开放函数
defineExpose({ f5 })
</script>
<style lang="scss" scoped>
.prescription-url img {
  width: 700px;
}
</style>